package zmee.pmas.form;

import kd.bos.dataentity.entity.DynamicObject;
import kd.bos.dataentity.entity.DynamicObjectCollection;
import kd.bos.dataentity.utils.StringUtils;
import kd.bos.entity.datamodel.IDataModel;
import kd.bos.entity.datamodel.events.ChangeData;
import kd.bos.entity.datamodel.events.PropertyChangedArgs;
import kd.bos.form.events.ClosedCallBackEvent;
import kd.bos.orm.query.QFilter;
import kd.bos.servicehelper.BusinessDataServiceHelper;
import kd.bos.servicehelper.QueryServiceHelper;
import kd.scm.common.util.SrmCommonUtil;
import kd.scm.pds.common.util.ExtParameterUtils;
import kd.scm.pds.common.util.MultiBasedataUtils;
import kd.scm.src.formplugin.comp.SrcSelectExpertHelper;

import java.util.*;

/**
 * @Author cb
 * @DateTime 2022/12/4 15:22
 * @Description 评标设置、编辑插件
 */
public class BidOpenConfigFormPlugin extends SrcSelectExpertHelper {

    @Override
    public void propertyChanged(PropertyChangedArgs e) {
        super.propertyChanged(e);
        String name = e.getProperty().getName();
        ChangeData changeData = e.getChangeSet()[0];
        if ("scorer".equals(name)) {
            DynamicObjectCollection newValue = (DynamicObjectCollection) changeData.getNewValue();
            DynamicObjectCollection entryentity = this.getModel().getEntryEntity("entryentity");
            for (DynamicObject entry : entryentity) {
                entry.set("scorer", newValue);
            }
            this.getView().updateView("entryentity");
        }
    }

    @Override
    public void closedCallBack(ClosedCallBackEvent e) {
        String actionId = e.getActionId();
        Object returnData = e.getReturnData();
        if (returnData instanceof Map) {
            if ("pds_selectexpert".equals(actionId)) {
                // 专家抽取 回调方法
                Map<String, Object> paramMap = (Map<String, Object>) returnData;
                DynamicObject dataEntity = this.getView().getParentView().getModel().getDataEntity(true);
                // 审核之后给生成的 开标准备 中的 评标设置单据体赋值
                List<String> typsList = new ArrayList<>();
                String billno = dataEntity.getString("billno");
                QFilter qFilterBillno = new QFilter("billno", "=", billno);
                // 查询 标书编制
                DynamicObject loadSingle = BusinessDataServiceHelper.loadSingle("src_biddoc", "id", new QFilter[]{qFilterBillno});
                if (null != loadSingle) {
                    Object pkValue = loadSingle.getPkValue();
                    QFilter qFilterParentid = new QFilter("parentid", "=", pkValue);
                    // 查询 采购方招标文件
                    DynamicObject biddocSrc = BusinessDataServiceHelper.loadSingle("src_biddoc_src",
                            "id,entryentity,entryentity.packfiletype", new QFilter[]{qFilterParentid});
                    if (null != biddocSrc) {
                        DynamicObjectCollection entryentity = biddocSrc.getDynamicObjectCollection("entryentity");
                        for (DynamicObject entry : entryentity) {
                            String packfiletype = entry.getString("packfiletype");
                            typsList.add(packfiletype);
                        }
                    }
                }
                // 查询中间表放入Map中
                Map<String, Long> bslxzblxMap = new HashMap<>();
                QFilter qFilter = new QFilter("billno", "=", "zmee_001");
                DynamicObjectCollection querys = QueryServiceHelper.query("zmee_bslxzblx",
                        "id,entryentity,entryentity.zmee_combofield,entryentity.zmee_basedatafield", new QFilter[]{qFilter});
                for (DynamicObject query : querys) {
                    bslxzblxMap.put(query.getString("entryentity.zmee_combofield"), query.getLong("entryentity.zmee_basedatafield"));
                }
                DynamicObjectCollection entryentity = this.getModel().getEntryEntity("entryentity");
                int count = typsList.size() - entryentity.size();
                if (count > 0) {
                    this.getModel().batchCreateNewEntryRow("entryentity", count);
                }
                for (int i = 0; i < typsList.size(); i++) {
                    Long indextypeId = bslxzblxMap.get(typsList.get(i));
                    paramMap.put("currentrow", i);
                    paramMap.put("indextypeId", indextypeId);
                    this.setScorerValue(paramMap);
                }
            }
        }
    }

    private void setScorerValue(Map<String, Object> paramMap) {
        Object currentRow = paramMap.get("currentrow");
        if (!StringUtils.isBlank(currentRow)) {
            int index = (Integer) currentRow;
            Set<Long> newExpertIds = (Set) paramMap.get("expertuser");
            if (newExpertIds != null && newExpertIds.size() != 0) {
                long sourceFlowId = SrmCommonUtil.getPkValue(this.getView().getParentView().getModel().getDataEntity().getDynamicObject("srctype"));
                boolean isOneRowPerExpert = ExtParameterUtils.convertToBoolen(ExtParameterUtils.getExtParameterValueById("pds_flowconfig", sourceFlowId, "isOneRowPerExpert", false,SrmCommonUtil.getPkValue(this.getView().getParentView().getModel().getDataEntity())));
                IDataModel model = this.getModel();
                boolean isAdd = (Boolean) (paramMap.get("isadd") == null ? false : paramMap.get("isadd"));
                if (isAdd && !isOneRowPerExpert) {
                    Set<Long> expertIds = MultiBasedataUtils.getBasedataIdSet(model.getEntryEntity("entryentity").get(index), "scorer");
                    newExpertIds.addAll(expertIds);
                }
                this.setScorerValue(model, newExpertIds, paramMap, index, isOneRowPerExpert);
            }
        }
    }

    private void setScorerValue(IDataModel model, Set<Long> newExpertIds, Map<String, Object> paramMap, int index, boolean isOneRowPerExpert) {
        if (!isOneRowPerExpert) {
            model.setValue("scorer", newExpertIds.toArray(new Object[0]), index);
            model.setValue("qfilter_tag", paramMap.get("condition"), index);
            model.setValue("indextype", paramMap.get("indextypeId"), index);
        } else {
            int rowCount = model.getEntryRowCount("entryentity");
            index = 999999;
            for (int i = 0; i < rowCount; ++i) {
                if (model.getEntryRowEntity("entryentity", i).getDynamicObjectCollection("scorer").size() == 0) {
                    index = i;
                    break;
                }
            }
            index = Math.min(index, rowCount);
            for (Iterator<Long> var11 = newExpertIds.iterator(); var11.hasNext(); ++index) {
                long newExpertId = var11.next();
                Object[] scoreIds = new Object[]{newExpertId};
                if (index >= rowCount) {
                    model.appendEntryRow("entryentity", index, 1);
                }
                model.setValue("scorer", scoreIds, index);
                model.setValue("qfilter_tag", paramMap.get("condition"), index);
                model.setValue("indextype", paramMap.get("indextypeId"), index);
            }
        }
    }
}